package NetCrossServer.thread;

import NetCrossServer.server.TcpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class ServerThread extends Thread {
    private static Logger logger = LoggerFactory.getLogger(ServerThread.class);
    private Socket socket;
    private BufferedReader br;
    private BufferedWriter bw;

    public ServerThread(Socket socket) throws IOException {
        this.socket = socket;
        this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    }

    @Override
    public void run() {
        InetAddress inetAddress = socket.getInetAddress();
        if (logger.isDebugEnabled()){
            logger.debug("this is new clint! ip:" + inetAddress.getHostAddress() + " port:" + socket.getPort());
        }
        try {
            bw.write("all clients :" + TcpServer.st.toString());
            String info = null;
            while((info = br.readLine()) != null){
                if (info.startsWith("connectClient_")){
                    String[] infoArr = info.split("_");
                    String ip = infoArr[1];
                    String port = infoArr[2];
                    if (logger.isDebugEnabled()){
                        logger.debug("net cross ip:" + ip);
                    }
                    for (ServerThread serverThread : TcpServer.st) {
                        Socket clientSocket = serverThread.socket;
                        if (clientSocket.getInetAddress().equals(ip) && clientSocket.getPort() == Integer.parseInt(port)) {
                            serverThread.bw.write("autoConn_" + socket.getInetAddress().getHostAddress() + "_" + socket.getPort()+"\n");
                            serverThread.bw.flush();
                            break;
                        }
                    }
                }else {
                    bw.write("welcome!" + info + "\n");
                    bw.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (logger.isDebugEnabled()){
                logger.debug("client is closed! ip:"+inetAddress.getHostAddress()+" port:"+socket.getPort());
            }
            TcpServer.st.remove(this);
            try {
                if (bw != null){
                    bw.close();
                }
                if (br != null){
                    br.close();
                }
                if (socket != null){
                    socket.close();
                }
            }catch (Exception e){

            }
        }
    }
}
